
"""
deque的一个使用场景是保存历史记录，使用deque的append方法
"""
#对一系列的文本行做简单的文本匹配工作，当发现有匹配时就输出当前的匹配行以及最后检查过的N行文本
#想要保存程序的状态，可以使用list，字典等数据类型，也可以使用生成器，生成器开销小

from collections import  deque

def search(lines,patterns,history=5):
    privel_lines=deque(maxlen=history)
    for line in lines:
        if patterns in line:
            yield line,privel_lines
        privel_lines.append(line)

if __name__ == '__main__':
    with open("test2.txt","r") as f:
        for oneline,prevlines in search(f,"python",5):
            for pline in prevlines:
                print(pline,end="")

            print(oneline,end="")
            print("_"*20)


def my_search(lines,patterns,history=5):
    privel_lines=deque(maxlen=history)
    lst=[]     #保存匹配的行和之前匹配过的行
    for line in lines:
        if patterns in line:
            lst.append((line,privel_lines.copy()))    #需要对deque做一次copy，原因是append的是引用，不然随后的值会发生变化
        privel_lines.append(line)
    return lst

if __name__ == '__main__':
    with open("test2.txt","r") as f:
        for oneline,prevlines in my_search(f,"python",5):
            for pline in prevlines:
                print(pline,end="")

            print(oneline,end="")
            print("_"*20)





